package com.winit.sg.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.bean.service.BeanService;
import com.winit.common.base.bean.ExecuteResult;
import com.winit.common.sg.AnalysisUtil;
import com.winit.common.zook.ZookUtil;
import com.winit.commons.util.SeqGenerate;
import com.winit.method.service.MethodService;
import com.winit.sg.mapper.SgServiceMapper;
import com.winit.sg.model.Sg;
import com.winit.sg.service.SgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wanglin on 2018/6/4.
 */
@Service(value = "sgService")
public class SgServiceImpl implements SgService {

    @Autowired
    SgServiceMapper sgServiceMapper;

    @Autowired
    BeanService beanService;
    @Autowired
    MethodService methodService;


    @Override
    public void SgModelInitJob(String dubboUrl) {
        List<String> list;
        try {
            if(StringUtils.isEmpty(dubboUrl)){
                list = ZookUtil.getZookInfo();
                for ( String li:list){
                    JSONObject json = AnalysisUtil.analysis(li);
                    //保存bean方法
                    beanService.batchSaveBean(json);
                    Sg sg = this.serviceInit(json);
                    methodService.batchSgSaveMethod(json.getJSONArray("method"),sg.getId());
                }
            }else{
                JSONObject js = AnalysisUtil.analysis(dubboUrl);
                beanService.batchSaveBean(js);
                Sg sg = this.serviceInit(js);
                methodService.batchSgSaveMethod(js.getJSONArray("method"),sg.getId());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询系统数据
     * @return
     */
    @Override
    public List<String> getSys(){
        return sgServiceMapper.getSys();
    }

    @Override
    public List<Sg> getServices(String sys) {
        Map map = new HashMap<>();
        map.put("sys",sys);
        return sgServiceMapper.getServices(map);
    }


    //保存service方法
    private Sg serviceInit(JSONObject jsonObject){
        JSONObject serviceJson = jsonObject.getJSONObject("service");
        Sg oldSg = sgServiceMapper.selectByPrimaryPath(serviceJson.getString("path"));
        if(oldSg!=null){
            return oldSg;
        }
        Sg sg = new Sg();
        sg.setId(SeqGenerate.createId("SGSE"));
        sg.setName(serviceJson.getString("name"));
        sg.setPath(serviceJson.getString("path"));
//        sg.setsDesc(serviceJson.getString("remarks"));
        sg.setSys(serviceJson.getString("sys"));
        sgServiceMapper.insertSelective(sg);
        return sg;
    }
}
